import { useState } from "react";

import store from "./redux";
import { increment, decrement } from "./redux/action";

function App() {
  // 收集表单数据
  const [val, setVal] = useState(1);
  const handleChange = (e) => {
    setVal(+e.target.value);
  };

  // 更新：加
  const handleIncrement = () => {
    // 1. 调用action函数生成action对象
    const action = increment(val);
    // 2. 调用store.dispatch(action) --> 触发 reducer 函数 -> 计算生成 newState 并更新
    // -> 触发 store.subscribe 的回调函数 -> 组件重新渲染获取最新数据展示
    store.dispatch(action);
  };

  const handleDecrement = () => {
    const action = decrement(val);
    store.dispatch(action);
  };

  const handleIncrementByOdd = () => {
    if (state % 2 === 1) {
      store.dispatch(increment(val));
    }
  };

  const handleIncrementByTimeout = () => {
    setTimeout(() => {
      store.dispatch(increment(val));
    }, 1000);
  };

  // 读取redux数据的方法
  const state = store.getState();

  return (
    <>
      <h1>点击次数：{state}</h1>
      <select onChange={handleChange}>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
      </select>
      <button onClick={handleIncrement}>增加</button>
      <button onClick={handleDecrement}>减少</button>
      <button onClick={handleIncrementByOdd}>奇数增加</button>
      <button onClick={handleIncrementByTimeout}>延长1s增加</button>
    </>
  );
}

export default App;
